package be.jprojects.subscription.gui.datamodels;
import java.util.Arrays;
import java.util.HashMap;

import javax.swing.table.AbstractTableModel;



public class HideColumnDataModel extends AbstractTableModel {
	protected String[] columnNames;
	private HashMap<String, Integer> titleMap;
	protected Object[][] data;
	protected boolean[] visibles;
	private int[] realColumn;
	private int columnCount;
	
	public HideColumnDataModel() {
		
	}
	
	public HideColumnDataModel(String[] columnNames, Object[][] data, boolean allvisible) {
		this.columnNames = columnNames;
		this.data = data;
		initMap(allvisible);
	}

	protected void initMap(boolean allvisible) {
		visibles = new boolean[columnNames.length];
		realColumn = new int[columnNames.length];
		titleMap = new HashMap<String, Integer>(2 * columnNames.length);
		for (int i=0; i<columnNames.length; i++) {
			titleMap.put(columnNames[i], i);
			visibles[i] = allvisible;
		}
		fillRealColumn();
		columnCount = columnNames.length ;
	}
	
	
	public int getColumnCount() { 
		return columnCount; 
	}
	
	public int getRowCount() { 
		return data.length;
	}
	
	public Object getValueAt(int row, int column) {
		return data[row][realColumn[column]];
	}
	@Override
	public String getColumnName(int column) {
		return columnNames[realColumn[column]];
	}
	@Override
	public Class getColumnClass(int column) {
		return getValueAt(0,column).getClass();
	}
	@Override
	public void setValueAt(Object aValue, int row, int column) {
		data[row][realColumn[column]] = aValue;
	}
	
	public String[] getColumnNames() {
		return columnNames;
	}


	public void setColumnNames(String[] columnNames) {
		this.columnNames = columnNames;
	}

	public void changeColumn(String source) {
		int column = titleMap.get(source);
		
		if (visibles[column]) {
			columnCount--;
		} else {
			columnCount++;
		}
		
		visibles[column] = !visibles[column];
		
		fillRealColumn();
		
		fireTableStructureChanged();
	}


	private void fillRealColumn() {
		int col=0;
		for (int c=0; c<columnNames.length; c++) {
			if (visibles[c]) {
				realColumn[col] = c;
				col++;
			}
		}
	}
	
	public boolean isVisible(int column) {
		return visibles[column];
	}
	
}
